package com.kevin.spider.service;

import com.kevin.spider.domain.bo.XhsNote;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.FileChooser;
import com.microsoft.playwright.Page;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.util.List;

/**
 * @author 张帆
 * @date 2025/6/16 17:56
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PublishXhsService extends BaseSpiderService {
    private String xhsHomeUrl = "https://ark.xiaohongshu.com/app-system/home";

    private String xhsPicNoteUrl = "https://creator.xiaohongshu.com/publish/publish?from=menu&target=pic";
    private String xhsVideoNoteUrl = "https://creator.xiaohongshu.com/publish/publish?from=menu&target=video";

    public void notePublish(XhsNote note, Page page) {
        page.navigate(xhsPicNoteUrl);

        uploadPic(note.getNotePics(), page);

        ElementHandle postPageContainer = getPostPageContainer(page);

        setNoteContent(postPageContainer, note);

        addGood(postPageContainer, page, note);

        saveDraft(postPageContainer);

    }

    private void setNoteContent(ElementHandle postPageContainer, XhsNote note) {
        //标题
        postPageContainer.waitForSelector("//div[contains(@class, 'titleInput')]")
                .querySelector("//input[@class='d-text']")
                .fill(note.getTitle());
        //正文
        postPageContainer.querySelector("//div[@id='quillEditor']/div/p")
                .fill(note.getContent());

        //postPageContainer.querySelector("//div[@id='quillEditor']/div/p").evaluate("node => node.innerHTML = '<em>动态更新的内容</em>'");
        //定时发布
        postPageContainer.querySelector("//span[contains(normalize-space(), '定时发布')]")
                .click();
    }

    @SneakyThrows
    private void uploadPic(List<File> picFiles, Page page) {

        // 监听文件选择对话框
        FileChooser fileChooser = page.waitForFileChooser(
                () -> {
                    page.waitForSelector("//input[@class='upload-input']")
                            .click();
                });
        page.waitForTimeout(1000);
        fileChooser.setFiles(picFiles.stream().map(File::toPath).toList().toArray(new Path[0]));
    }

    private ElementHandle getPostPageContainer(Page page) {
        return page.querySelector("//div[@class='post-page']");
    }

    private void addGood(ElementHandle postPageContainer, Page page, XhsNote note) {
        if(note.getGood() == null) {
            return;
        }

        postPageContainer.querySelector("//div[@class='media-commodity']")
                .querySelector("//span[contains(normalize-space(), '添加商品')]")
                .click();

       ElementHandle modal = page.querySelector("//div[@class='d-modal-mask']");
       modal.querySelector("input[contains(@class, 'd-text') and contains(@placeholder, '搜索商品')]")
                .fill(note.getGood().getGoodId());

        page.waitForTimeout(1000);

        modal.waitForSelector("//div[@class='goods-list-normal']")
                .querySelector("//div[@class='good-card-container']")
                .querySelector("div[contains(@class, 'good-selected')]")
                .click();

        modal.querySelector("//span[contains(normalize-space(), '保存')]");

    }

    private void submit(ElementHandle postPageContainer) {
        postPageContainer.querySelector("//div[@class='submit']")
                .querySelector("//span[contains(normalize-space(), '发布')]")
                .click();
    }

    private void saveDraft(ElementHandle postPageContainer) {
        postPageContainer.querySelector("//div[@class='submit']")
                .querySelector("//span[contains(normalize-space(), '暂存离开')]")
                .click();
    }

}
